package com.situ.water_read.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.water_pay.mapper.PyBillMapper;
import com.situ.water_pay.mapper.PyBilldetailMapper;
import com.situ.water_pay.pojo.PyBill;
import com.situ.water_pay.pojo.PyBilldetail;
import com.situ.water_read.mapper.RdChangemaxvalueMapper;
import com.situ.water_read.mapper.RdReadtypesMapper;
import com.situ.water_read.mapper.RdVolumeMapper;
import com.situ.water_read.pojo.*;
import com.situ.water_read.mapper.RdReadMapper;
import com.situ.water_read.service.RdReadService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.water_system.mapper.SyCosttypeMapper;
import com.situ.water_system.mapper.SyEmpMapper;
import com.situ.water_system.pojo.SyCosttype;
import com.situ.water_system.pojo.SyEmp;
import com.situ.water_user.mapper.UsFormulaMapper;
import com.situ.water_user.mapper.UsUserMapper;
import com.situ.water_user.pojo.UsFormula;
import com.situ.water_user.pojo.UsUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Wrapper;
import java.text.DecimalFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Angel
 * @since 2020-12-01
 */
@Service
public class RdReadServiceImpl extends ServiceImpl<RdReadMapper, RdRead> implements RdReadService {
    @Autowired
    private RdReadMapper mapper;
    @Autowired
    private RdVolumeMapper volumeMapper;
    @Autowired
    private RdChangemaxvalueMapper maxmapper;
    @Autowired
    private RdReadtypesMapper typemapper;
    @Autowired
    private UsFormulaMapper formulaMapper;
    @Autowired
    private PyBillMapper billMapper;
    @Autowired
    private SyCosttypeMapper costmapper;
    @Autowired
    private PyBilldetailMapper detailMapper;
    @Autowired
    private UsUserMapper userMapper;
    @Autowired
    private SyEmpMapper empMapper;
    @Override
    public List<RdRead> queryall() {
        return mapper.selectList(null);
    }

    /**
     * 查询抄表录入中的下拉框
     * @return
     */
    @Override
    public List<Map> queryarea() {
        Calendar cal = Calendar.getInstance();
        Map map=new HashMap();
        map.put("year",cal.get(Calendar.YEAR));
        map.put("month",cal.get(Calendar.MONTH)+1);
        map.put("id",1);
        return volumeMapper.queryarea(map);
    }

    @Override
    public List<Map> queryvolume(Integer id) {
        if(id==null){
            id=1;
        }
            Calendar cal = Calendar.getInstance();
            Map map=new HashMap();
            map.put("year",cal.get(Calendar.YEAR));
            map.put("month",cal.get(Calendar.MONTH)+1);
            map.put("id",id);
        return volumeMapper.queryvolume(map);
    }

    @Override
    public RdVolume querybyVolumeID(Integer volumeID) {
        return volumeMapper.selectById(volumeID);
    }

    /**
     * 查询本月该表册用户的具体信息
     * @param volumeID
     * @return
     */
    @Override
    public List<Map> queryReadbyID(Integer volumeID) {
        Calendar cal = Calendar.getInstance();
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("ReadYear",cal.get(Calendar.YEAR));
        wrapper.eq("ReadMonth",cal.get(Calendar.MONTH)+1);
        wrapper.eq("rd.VolumeId",volumeID);
        List<Map> list = mapper.selectListReadUser(wrapper);
        return list;
    }

    /**
     * 查询 该月表册用户总数
     * @param volumeID
     * @return
     */
    @Override
    public Integer selectCount(Integer volumeID) {
        Calendar cal = Calendar.getInstance();
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("ReadYear",cal.get(Calendar.YEAR));
        wrapper.eq("ReadMonth",cal.get(Calendar.MONTH)+1);
        wrapper.eq("VolumeId",volumeID);
        Integer count = mapper.selectCount(wrapper);
        return count;
    }
    @Transactional
    @Override
    public void updatereadById(RdRead read) {
        mapper.updateById(read);
    }

    @Override
    public void updateAudit(Integer id) {
        mapper.updateAudit(id);
    }

    /**
     * 修改抄表数据中的最大码值
     * @param read
     * @return
     */
    @Override
    public int updateMax(RdRead read) {
        return mapper.updateById(read);
    }

    /**
     * 添加最大码修改值
     * @param read
     * @return
     */
    @Override
    public int addChangeMax(RdRead read,Integer empid) {
        Date date = new Date();
        RdChangemaxvalue max=new RdChangemaxvalue();
        max.setDatee(date);
        //获取当前sessionId
        max.setEmpID(empid);
        max.setUserNo(read.getUserNo());
        max.setMeterNo(read.getMeterNo());
        max.setMaxValue1(read.getBeforeMax());
        max.setMaxValue2(read.getMaxValue());
        return maxmapper.insert(max);
    }

    /**
     *通过表册Id查询表册
     * @param id
     * @return
     */
    @Override
    public RdRead querybyID(Integer id) {
        return mapper.selectById(id);
    }

    /**
     * 添加分类水量
     * @param read
     */
    @Override
    public void insertReadTypes(RdRead read) {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("UserNo",read.getUserNo());
        List<UsFormula> list = formulaMapper.selectList(wrapper);
        list.forEach(x-> System.out.println(x.toString()));
        boolean haveNum=false;
        Integer sum=0;
        for(int i=0;i<list.size();i++){
            Integer allotType = list.get(i).getAllotType();
            if(allotType==0){
                haveNum=true;
                System.out.println("有数字");
                break;
            }
        }
        boolean perNum=false;
        for(int i=0;i<list.size();i++){
            Integer allotType = list.get(i).getAllotType();
            if(allotType==1){
                perNum=true;
                System.out.println("有百分比");
                break;
            }
        }
        boolean surNum=false;
        Integer serId=0;
        for(int i=0;i<list.size();i++){
            Integer allotType = list.get(i).getAllotType();
            if(allotType==2){
                serId=list.get(i).getId();
                surNum=true;
                System.out.println("有剩余");
                break;
            }
        }
        System.out.println("bool值"+haveNum+" "+perNum+" "+surNum);
        RdReadtypes RdType=new RdReadtypes();
        if(haveNum){//有数字
            if(perNum){//有百分比
                wrapper.eq("AllotType",0);
                List<UsFormula> Numlist = formulaMapper.selectList(wrapper);
                Integer nextmin;
                if(Numlist.size()>1){
                    RdType.setReadID(read.getReadEmpID());
                    RdType.setUserNo(read.getUserNo());
                    RdType.setWaterTypeCode(Numlist.get(0).getWaterTypeCode());
                    RdType.setAllotText(Numlist.get(0).getAllotText());
                    Integer minval=Math.min(Numlist.get(0).getAllotValue(),read.getAmount());
                    RdType.setAmount(Math.min(Numlist.get(0).getAllotValue(),read.getAmount()));
                    typemapper.insert(RdType);
                    nextmin=read.getAmount()-minval;
                    for(int i=1;i<Numlist.size();i++) {
                        RdType.setReadID(read.getReadEmpID());
                        RdType.setUserNo(read.getUserNo());
                        RdType.setWaterTypeCode(Numlist.get(i).getWaterTypeCode());
                        RdType.setAllotText(Numlist.get(i).getAllotText());
                        RdType.setAmount(Math.min(Numlist.get(i).getAllotValue(), nextmin));
                        nextmin = nextmin - Math.min(Numlist.get(i).getAllotValue(), nextmin);
                        typemapper.insert(RdType);
                    }
                }else{
                    RdType.setReadID(read.getReadEmpID());
                    RdType.setUserNo(read.getUserNo());
                    RdType.setWaterTypeCode(Numlist.get(0).getWaterTypeCode());
                    RdType.setAllotText(Numlist.get(0).getAllotText());
                    nextmin=Math.min(Numlist.get(0).getAllotValue(),read.getAmount());
                    RdType.setAmount(Math.min(Numlist.get(0).getAllotValue(),read.getAmount()));
                    nextmin=read.getAmount()-nextmin;
                    typemapper.insert(RdType);
                }
                QueryWrapper perwrapper=new QueryWrapper();
                perwrapper.eq("UserNo",read.getUserNo());
                perwrapper.eq("AllotType",1);
                List<UsFormula> perlist = formulaMapper.selectList(perwrapper);
                if(surNum){
                    for (int i=0;i<perlist.size();i++){
                        RdType.setReadID(read.getReadEmpID());
                        RdType.setUserNo(read.getUserNo());
                        RdType.setWaterTypeCode(perlist.get(i).getWaterTypeCode());
                        RdType.setAllotText(perlist.get(i).getAllotText());
                        RdType.setAmount(Math.round(nextmin*perlist.get(i).getAllotValue()/(float)100));
                        typemapper.insert(RdType);
                        nextmin-=Math.round(nextmin*perlist.get(i).getAllotValue()/(float)100);
                    }
                    for (int i=0;i<list.size();i++){
                        if (serId==list.get(i).getId()){
                            RdType.setReadID(read.getReadEmpID());
                            RdType.setUserNo(read.getUserNo());
                            RdType.setWaterTypeCode(list.get(i).getWaterTypeCode());
                            RdType.setAllotText(list.get(i).getAllotText());
                            RdType.setAmount(Math.round(nextmin));
                            typemapper.insert(RdType);
                        }
                    }
                }else{
                    if(perlist.size()>1){
                        for (int i=0;i<perlist.size()-1;i++){
                            RdType.setReadID(read.getReadEmpID());
                            RdType.setUserNo(read.getUserNo());
                            RdType.setWaterTypeCode(perlist.get(i).getWaterTypeCode());
                            RdType.setAllotText(perlist.get(i).getAllotText());
                            RdType.setAmount(Math.round(nextmin*perlist.get(i).getAllotValue()/(float)100));
                            typemapper.insert(RdType);
                            nextmin-=Math.round(nextmin*perlist.get(i).getAllotValue()/(float)100);
                        }
                        RdType.setReadID(read.getReadEmpID());
                        RdType.setUserNo(read.getUserNo());
                        RdType.setWaterTypeCode(perlist.get(perlist.size()-1).getWaterTypeCode());
                        RdType.setAllotText(perlist.get(perlist.size()-1).getAllotText());
                        RdType.setAmount(Math.round(nextmin));
                        typemapper.insert(RdType);
                    }else{
                        RdType.setReadID(read.getReadEmpID());
                        RdType.setUserNo(read.getUserNo());
                        RdType.setWaterTypeCode(perlist.get(0).getWaterTypeCode());
                        RdType.setAllotText(perlist.get(0).getAllotText());
                        RdType.setAmount(nextmin);
                        typemapper.insert(RdType);
                    }
                }

            }else{
                //
            }
        }else{
            if(surNum) {//有*
                if (list.size() > 1) {
                    sum=read.getAmount();
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).getId() != serId) {
                            RdType.setReadID(read.getReadEmpID());
                            RdType.setUserNo(read.getUserNo());
                            RdType.setWaterTypeCode(list.get(i).getWaterTypeCode());
                            RdType.setAllotText(list.get(i).getAllotText());
                            RdType.setAmount(Math.round(read.getAmount() * (list.get(i).getAllotValue()/(float)100)));
                            System.out.println(list.get(i).getAllotValue()+" "+(list.get(i).getAllotValue()/(float)100)+" "+read.getAmount()+" "+"每个分类用水量："+Math.round(read.getAmount() * (list.get(i).getAllotValue()/(float)100)));
                            sum -= Math.round(read.getAmount() * (list.get(i).getAllotValue()/(float)100));
                            typemapper.insert(RdType);
                        } else {
                            RdType.setReadID(read.getReadEmpID());
                            RdType.setUserNo(read.getUserNo());
                            RdType.setWaterTypeCode(list.get(i).getWaterTypeCode());
                            RdType.setAllotText(list.get(i).getAllotText());
                            RdType.setAmount(sum);
                            System.out.println("剩余用水量"+sum);
                            typemapper.insert(RdType);
                        }
                    }
                }else {
                    sum=read.getAmount();
                    RdType.setReadID(read.getReadEmpID());
                    RdType.setUserNo(read.getUserNo());
                    RdType.setWaterTypeCode(list.get(0).getWaterTypeCode());
                    RdType.setAllotText(list.get(0).getAllotText());
                    RdType.setAmount(sum);
                    typemapper.insert(RdType);
                }
            }else{
                if (list.size() > 1) {
                    sum=read.getAmount();
                    for (int i = 0; i < list.size(); i++) {
                        if(i!=list.size()-1) {
                            RdType.setReadID(read.getReadEmpID());
                            RdType.setUserNo(read.getUserNo());
                            RdType.setWaterTypeCode(list.get(i).getWaterTypeCode());
                            RdType.setAllotText(list.get(i).getAllotText());
                            RdType.setAmount(Math.round(read.getAmount() * (list.get(i).getAllotValue() / (float) 100)));
                            sum -= Math.round(read.getAmount() * (list.get(i).getAllotValue() / (float) 100));
                            typemapper.insert(RdType);
                        }else{
                            RdType.setReadID(read.getReadEmpID());
                            RdType.setUserNo(read.getUserNo());
                            RdType.setWaterTypeCode(list.get(i).getWaterTypeCode());
                            RdType.setAllotText(list.get(i).getAllotText());
                            RdType.setAmount(sum);
                            typemapper.insert(RdType);
                        }
                    }
                }else{
                    RdType.setReadID(read.getReadEmpID());
                    RdType.setUserNo(read.getUserNo());
                    RdType.setWaterTypeCode(list.get(0).getWaterTypeCode());
                    RdType.setAllotText(list.get(0).getAllotText());
                    RdType.setAmount(Math.round(read.getAmount() * (list.get(0).getAllotValue() / (float) 100)));
                    typemapper.insert(RdType);
                }
            }
        }

        //boolean bool = read.getFormula().contains("%");
//        if(!bool){
//
//        }
        //判断是否包含

//        String formula = read.getFormula();
//        String replace = formula.replace("[", " ");
//        System.out.println(replace);
    }

    @Override
    public void updatePre(RdRead read) {
        mapper.updateById(read);
    }

    @Override
    public List<Map> queryAllDate() {
        return mapper.queryAllDate();
    }

    @Override
    public List<Map> queryAuditByID(Integer volumeId) {
        RdRead read=new RdRead();
        Calendar cal = Calendar.getInstance();
        read.setVolumeId(volumeId);
        read.setReadMonth(cal.get(Calendar.MONTH)+1);
        read.setReadYear(cal.get(Calendar.YEAR));
        return mapper.queryAuditByID(read);
    }

    @Override
    public void updateAduittrue(String s,Integer empId) {
        RdRead read=new RdRead();
        read.setId(Integer.parseInt(s));
        read.setAudit(true);
        read.setAuditEmpID(empId);
        read.setAuditDate(new Date());
        mapper.updateById(read);
    }
    @Transactional
    @Override
    public void addPy(RdRead read) {
        Double FJF;
        Boolean SH=false;
        Integer SHNum=0;
        Integer sumNum=0;
        Double sumMoney=0.0;
        Calendar cal = Calendar.getInstance();
        QueryWrapper wrapper=new QueryWrapper();
    wrapper.eq("ReadID",read.getId());
    List<RdReadtypes> list = typemapper.selectList(wrapper);//查询分类用水量

        PyBilldetail detail=new PyBilldetail();
        //循环添加分类用水表中的用水类型
        for (int i=0;i<list.size();i++){
            detail.setBillNo("SF"+read.getUserNo()+read.getReadYear()+read.getReadMonth());
            detail.setUserNo(read.getUserNo());
            detail.setCostTypeCode(list.get(i).getWaterTypeCode());
            detail.setAmount(list.get(i).getAmount());
            QueryWrapper costwrapper=new QueryWrapper();
            costwrapper.eq("Code",list.get(i).getWaterTypeCode());
            SyCosttype costtype = costmapper.selectOne(costwrapper);
            detail.setPrice(costtype.getPrice());
            detail.setDetailMoney(costtype.getPrice()*list.get(i).getAmount());
            sumNum+=list.get(i).getAmount();
            sumMoney+=costtype.getPrice()*list.get(i).getAmount();
            if (list.get(i).getWaterTypeCode()=="SH" || list.get(i).getWaterTypeCode().equals("SH")){
                SHNum=list.get(i).getAmount();
                SH=true;
            }
            detailMapper.insert(detail);
        }
        System.out.println("SH"+SH);
        if(SH){
            QueryWrapper costwrapper=new QueryWrapper();
            costwrapper.eq("Code","LJF");
            SyCosttype costtype = costmapper.selectOne(costwrapper);
            System.out.println("LJF"+costtype.getCode());
            detail.setCostTypeCode(costtype.getCode());
            detail.setAmount(SHNum);
            detail.setPrice(costtype.getPrice());
            detail.setDetailMoney(costtype.getPrice()*SHNum);
            sumMoney+=costtype.getPrice()*SHNum;
            detailMapper.insert(detail);
        }
            if (list.size()>0){
                QueryWrapper costwrapper=new QueryWrapper();
                costwrapper.eq("Code","WSF");
                SyCosttype costtype = costmapper.selectOne(costwrapper);
                detail.setCostTypeCode(costtype.getCode());
                detail.setAmount(sumNum);
                detail.setPrice(costtype.getPrice());
                detail.setDetailMoney(sumNum*costtype.getPrice());
                sumMoney+=sumNum*costtype.getPrice();
                detailMapper.insert(detail);
                QueryWrapper costwrapper1=new QueryWrapper();
                costwrapper1.eq("Code","ZYF");
                 costtype = costmapper.selectOne(costwrapper1);
                detail.setCostTypeCode(costtype.getCode());
                detail.setAmount(sumNum);
                detail.setPrice(costtype.getPrice());
                detail.setDetailMoney(sumNum*costtype.getPrice());
                sumMoney+=sumNum*costtype.getPrice();
                detail.setBalance(false);
                detail.setRealMoney(0.00);
                detailMapper.insert(detail);
            }
            PyBill bill=new PyBill();
            bill.setBillNo("SF"+read.getUserNo()+read.getReadYear()+read.getReadMonth());
            bill.setReadID(read.getId());
            bill.setUserNo(read.getUserNo());
            bill.setCreateDate(new Date());
            bill.setBillMoney(sumMoney);
            bill.setRealMoney(0.00);
            bill.setBalance(false);
            billMapper.insert(bill);

      //  DecimalFormat df = new DecimalFormat("#.00");
        UsUser user = userMapper.selectById(read.getUserNo());
        user.setUserMoney(user.getUserMoney()-sumMoney);
        userMapper.updateById(user);
    }

    @Override
    public IPage<Map> queryReadAll(Page<RdRead> page, RdRead read) {
        IPage<Map> map=mapper.queryReadAll(page,read);
        return map;
    }

    @Override
    public Integer selectSum(RdRead read) {
        return mapper.selectSum(read);
    }

    @Override
    public List<Map> queryVolumeAll(Integer year, Integer month) {
        return mapper.queryVolumeAll(year,month);
    }

    @Override
    public IPage<Map> queryReadZero(Page<RdRead> page, RdRead read) {
        return mapper.queryReadZero(page,read);
    }

    @Override
    public Integer queryReadZeroSum(RdRead read) {
        return mapper.queryReadZeroSum(read);
    }

    @Override
    public List<SyEmp> queryemp() {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("Remark","抄表员");
        return empMapper.selectList(wrapper);
    }

    @Override
    public IPage<Map> metervalue(Page<Map> page, Date month) {
        return userMapper.metervalue(page,month);
    }

    /**
     * fwj
     * @param userNo
     * @return
     */
    @Override
    public List<Map> queryUserNo(String userNo) {
        return mapper.queryUserNo(userNo);
    }

    @Override
    public List<Map> queryAuditByUserNo(String  userNO) {
        return mapper.queryAuditByUserNo(userNO);
    }

    @Override
    public UsUser querybyuserNo(QueryWrapper wrapper) {
        return userMapper.selectOne(wrapper);
    }

    @Override
    public List<Map> querywater() {
        Date date = new Date();
        Map map=new HashMap();
        map.put("date",date);
        List<Map> list=mapper.querywater(map);
        return list;
    }

//    public static void main(String[] args) {
//        Calendar instance = Calendar.getInstance();
//        instance.add(Calendar.MONTH,1);
//
//        System.out.println(instance.get(Calendar.YEAR)+" "+instance.get(Calendar.MONTH));
//    }
}
